//
//  NImageGridCell.m
//  IconMaster
//
//  Created by nhn on 14-10-10.
//  Copyright (c) 2014年 为为. All rights reserved.
//

#import "NImageGridCell.h"
#import <QuartzCore/QuartzCore.h>

#define MARGIN_LEFT 10
#define MARGIN_RIGHT MARGIN_LEFT
#define MARGIN_TOP  10
#define MARGIN_BOTTOM MARGIN_TOP
#define IMAGE_WIDTH (KWidth - 5*MARGIN_LEFT)/4
#define IMAGE_HEIGHT IMAGE_WIDTH
#define NUM_IMAGE 4
#define CORNER_RADIUS 12

#define DELETE_BUTTON_CENTER_X 10
#define DELETE_BUTTON_CENTER_Y 10
#define DELETE_BUTTON_WIDTH 26
#define DELETE_BUTTON_HEIGHT 26
#define DELETE_BUTTON_TAG 101
#define DELETE_BUTTON_IMAGE @"btn_delete.png"

@interface NImageGridCell ()

@property (nonatomic, strong) NSMutableArray* imageViewArray;

@end

@implementation NImageGridCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    if (self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        [self initImageView];
		[self initContentView];
    }
    return self;
}

- (void)initImageView
{
    self.imageViewArray = [NSMutableArray array];
    int startX = MARGIN_LEFT;
    int offsetX = (KWidth-MARGIN_LEFT-MARGIN_RIGHT-IMAGE_WIDTH)/(NUM_IMAGE-1);
    for (int i=0; i<NUM_IMAGE; i++) {
        CGRect frame = CGRectMake(startX+offsetX*i, MARGIN_TOP, IMAGE_WIDTH, IMAGE_HEIGHT);
        UIImageView* imageView = [[UIImageView alloc] initWithFrame:frame];
        [self.imageViewArray addObject:imageView];
        [self.contentView addSubview:imageView];
        imageView.backgroundColor = [UIColor whiteColor];
        imageView.layer.cornerRadius = CORNER_RADIUS;
        imageView.layer.masksToBounds = true;
        
        imageView.userInteractionEnabled = TRUE;
        UIGestureRecognizer* tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imageButtonPressed:)];
        [imageView addGestureRecognizer:tapGesture];
        
        UIGestureRecognizer* longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(imageLongPressed:)];
        [imageView addGestureRecognizer:longPress];
        UIButton* deleteButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [deleteButton addTarget:self action:@selector(deleteButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
        [deleteButton setImage:[UIImage imageNamed:DELETE_BUTTON_IMAGE] forState:UIControlStateNormal];
        deleteButton.tag = DELETE_BUTTON_TAG;
        deleteButton.frame = CGRectMake(0, 0, DELETE_BUTTON_WIDTH, DELETE_BUTTON_HEIGHT);
        deleteButton.center = CGPointMake(DELETE_BUTTON_CENTER_X, DELETE_BUTTON_CENTER_Y);
        deleteButton.hidden = true;
        [imageView addSubview:deleteButton];
    }
}

- (void)initContentView
{
	UITapGestureRecognizer* tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(contentViewPressed:)];
	tapGesture.numberOfTapsRequired = 1;
	[self.contentView addGestureRecognizer:tapGesture];
}

- (void)prepareForReuse
{

}

- (void)awakeFromNib {
    // Initialization code
}

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    [super setSelected:selected animated:animated];

    // Configure the view for the selected state
}

- (void)setImageArray:(NSArray *)imageArray
{
    for (UIImageView* imageView in self.imageViewArray) {
        imageView.hidden = true;
    }
    
    for (int i=0; i<self.imageViewArray.count && i<imageArray.count; i++) {
        UIImage* image = [imageArray objectAtIndex:i];
        [self setNewImage:image forIndex:i];
    }
//	NSLog(@"deleting %d", self.deleting);
}

- (void)setDeletable:(BOOL)deletable
{
    if (_deletable != deletable) {
        _deletable = deletable;
        if (_deletable) {
            for (UIImageView* imageView in self.imageViewArray) {
                imageView.clipsToBounds = NO;
            }
        } else {
            for (UIImageView* imageView in self.imageViewArray) {
                imageView.clipsToBounds = YES;
            }
        }
    }
}

- (void)setDeleting:(BOOL)deleting
{
	if (_deleting != deleting) {
		_deleting = deleting;
		if (deleting) {
			[self startDeleteAnimation];
		} else {
			[self stopDeleteAnimation];
		}
	}
}

- (void)setNewImage:(UIImage *)image forIndex:(int)index
{
    if (!image || index<0 || index>=self.imageViewArray.count) {
        return;
    }
    
    UIImageView* imageView = [self.imageViewArray objectAtIndex:index];
    [imageView setImage:image];
    imageView.hidden = false;
}

- (void)contentViewPressed:(id)sender
{
	self.deleting = NO;
	if (self.imageEndDeleteBlock) {
		self.imageEndDeleteBlock(self);
	}
}

- (void)imageButtonPressed:(id)sender
{
	if (self.deleting) {
		self.deleting = NO;
		if (self.imageEndDeleteBlock) {
			self.imageEndDeleteBlock(self);
		}
	} else {
		if (self.imagePressedBlock) {
            UIImageView* imageView = (UIImageView*)((UIGestureRecognizer*)sender).view;
            NSUInteger index = [self.imageViewArray indexOfObject:imageView];
            if (self.imagePressedBlock) {
                self.imagePressedBlock(self, imageView.image, index);
            }
		}
	}
}

- (void)imageLongPressed:(UILongPressGestureRecognizer*)gestureRecognizer
{
    if (!self.deletable) {
        return;
    }
    
    if (self.deleting) {
        return;
    }
    
	if (gestureRecognizer.state ==  UIGestureRecognizerStateBegan) {
		self.deleting = YES;
		if (self.imageBeginDeleteBlock) {
			self.imageBeginDeleteBlock(self);
		}
	}
}

- (void)deleteButtonPressed:(id)sender
{
    UIView* view = (UIView*)sender;
    UIImageView* imageView= (UIImageView*)view.superview;
    
    imageView.hidden = TRUE;
    
    if (self.imageDeletedBlock) {
        NSUInteger index = [self.imageViewArray indexOfObject:imageView];
        self.imageDeletedBlock(self, imageView.image, index);
    }
}

- (void)startDeleteAnimation
{
    for (UIImageView* imageView in self.imageViewArray) {
        UIView* deleteButton = [imageView viewWithTag:DELETE_BUTTON_TAG];
        deleteButton.hidden = false;
        
        srand([[NSDate date] timeIntervalSince1970]);
        float rand=(float)random();
        CFTimeInterval t=rand*0.0000000001;
        [UIView animateWithDuration:0.1
                              delay:t
                            options:0
                         animations:^{
                             imageView.transform=CGAffineTransformMakeRotation(-0.05);
                         }
                         completion:^(BOOL finished){
                             [UIView animateWithDuration:0.1
                                                   delay:0
                                                 options:UIViewAnimationOptionRepeat|UIViewAnimationOptionAutoreverse|UIViewAnimationOptionAllowUserInteraction
                                              animations:^{
                                                  imageView.transform=CGAffineTransformMakeRotation(0.05);
                                              }
                                              completion:nil];
                         }];
    }
}

- (void)stopDeleteAnimation
{
    for (UIImageView* imageView in self.imageViewArray) {
        UIView* deleteButton = [imageView viewWithTag:DELETE_BUTTON_TAG];
        deleteButton.hidden = true;
        
        [UIView animateWithDuration:0.1
                              delay:0.0
                            options:UIViewAnimationOptionAllowUserInteraction|UIViewAnimationOptionBeginFromCurrentState
                         animations:^{
                             imageView.transform = CGAffineTransformIdentity;
                         }
                         completion:^(BOOL finished) {
                             
                         }];
    }
}

+ (NSUInteger)height
{
    NSUInteger result = MARGIN_TOP+MARGIN_BOTTOM+IMAGE_HEIGHT;
    return result;
}

+ (NSUInteger)imagesPerRow
{
    return NUM_IMAGE;
}

@end
